package 滑动窗口;

public class 将x减到0的最小操作数4 {
    //https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/description/
    public int minOperations(int[] nums, int x) {
        int tmp = 0;
        //for(int i = 0; i < nums.length; i++) {
        // tmp += nums[i];
        //}
        for(int a : nums) {
            tmp += a;
        }
        int left = 0, right = 0, target = tmp - x, ret = -1, sum = 0;
        if(target < 0) {
            return -1;
        }
        if(target == 0) {
            return nums.length;
        }
        while(right < nums.length) {
            sum += nums[right];//最开始先鲁莽进窗口，也是最开始窗口和为0
            while(sum > target) {
                sum -= nums[left++];
            }
            if(sum == target) {
                ret = Math.max(right - left + 1, ret);
                sum -= nums[left++];
            }
            right++;
        }
        if(ret == -1) {
            return ret;
        }
        return nums.length - ret;
    }
}
